<?php

namespace App\Services\WechatApi;

class WechatApiOauth extends WechatApiBase
{
    // 组装网页授权url，返回给到用户进行授权
    // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
    public function getUserOauthUrl($appid, $callback_url, $scope = 'snsapi_userinfo', $state = 'state')
    {
        $redirect_uri = urlencode($callback_url);
        $other        = "response_type=code&scope={$scope}&state={$state}#wechat_redirect";

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&{$other}";

        return $url;
    }

    // 用户同意授权后拿到code，基于code获取access_token
    // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
    public function oauthUser($appid, $secret, $code)
    {
        $api = "sns/oauth2/access_token";

        return $this->send($api, [
            'appid' => $appid,
            'secret' => $secret,
            'code' => $code,
            'grant_type' => 'authorization_code'
        ], 'get');
    }

    // 获取用户基本信息
    // https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId
    public function userInfo($access_token, $openid)
    {
        $api = "cgi-bin/user/info";

        return $this->send($api, [
            'access_token' => $access_token,
            'openid'       => $openid,
            'lang'         => 'zh_CN',
        ], 'get');
    }
}
